package com.example.queue;

public class ArrayQueue {
    private int real;
    private int front;
    private int maxSize;
    private int queue[];

    public ArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.queue = new int[maxSize];
    }

    // 判断队列是否满了
    public boolean isFull() {
        return (this.real + 1) % maxSize == front;
    }

    // 判断队列是否为空
    public boolean isEmpty() {
        return this.front == this.real;
    }

    // 向队列中添加数据
    public void addQueue(int number) {
        if (this.isFull()) {
            System.out.println("队列已满，无法继续添加数据");
        }else{
            queue[real] = number;
            real = (real+1)%maxSize;
        }
    }

    public int getQueueValue() {
        if (isEmpty()) {
            throw new RuntimeException("队列为空，请添加数据后重试");
        }
        int tempIndex = front;
        // 为什么添加和获取，都要对头和尾取余？因为它是个环形数组，一旦头尾的数大于了数组最大值，就要取余重置为最初的状态
        front = (front+1) % maxSize;
        return this.queue[tempIndex];
    }

    public void showQueueValue() {
        if (isEmpty()) {
            System.out.println("队列中没有数据");
        } else {
            for (int i = front; i < front + size(); i++) {
                System.out.printf("array[%d]=%d\n", i%maxSize, queue[i%maxSize]);
            }
        }
    }

    public int headQueue() {
        if (isEmpty()) {
            System.out.println("队列暂无数据");
        }
        return queue[front];
    }

    public int size() {
        return (real + maxSize - front) % maxSize;
    }

}
